function [F,g] = funcde(p)
% FUNCDE - 将常微分方程化为优化问题后的优化函数
%   
    [err,u,v,w]= check(p);

    if err,
        error('input error')
    end
    x = [1 1.5 2];
    r = zeros(3,1);
    for i =1:3
        for j = 1:3,
            ewu = exp(w(j)*x(i)-u(j));
            r(i)=r(i)+v(j)/(1+ewu)-(x(i)-1)*(ewu*v(j)*w(j))/(1+ewu)^2;
            r(i)=r(i)+(1-1/x(i))*v(j)/(1+ewu);
        end
        r(i)=r(i)-x(i)^3+2/(5*x(i));
    end
    F = sum(r.^2);
    
    if nargout>1,
        g = zeros(9,1);
        pr  = zeros(9,3);
        pur = zeros(3,3);
        pvr = zeros(3,3);
        pwr = zeros(3,3);
        for i = 1:3
            for j = 1:3
                expt = exp(-u(j)+x(i)*w(j));
                pur(j,i) = expt*v(j)/(1+expt)^2+expt*(x(i)-1)*v(j)/((1+expt)^2 *x(i));
                pur(j,i) = pur(j,i)+(x(i)-1)*(2*expt*v(j)*w(j)/(1+expt)^3-expt*v(j)*w(j)/(1+expt)^2 );

                pvr(j,i) = (2*x(i)-1)/(x(i)*(1+expt)) - expt*(x(i)-1)*w(j)/(1+expt)^2;
                
                pwr(j,i) = - expt*v(j)*(-2-x(i)*(-3+w(j))+x(i)^2*w(j))/(1+expt)^2;
                pwr(j,i) = pwr(j,i)+2*(x(i)-1)*expt*x(i)*v(j)*w(j)/(1+expt)^3;
            end
        end
        pr(1:3,:)=pur;
        pr(4:6,:)=pvr;
        pr(7:9,:)=pwr;
        
        for i = 1:3
            g = g+r(i)*pr(:,i);
        end
        g = 2*g;
    end
    
end

function [err,u,v,w] = check(x)
% CHECK - 检测输入变量
%   
    err = 0; sx = size(x); n = max(sx);
    if  (min(sx) ~= 1) |n~=9| ~isreal(x) | any(isnan(x(:))) | isinf(norm(x(:))) 
        err = -1; 
    end
    if err == 0,
        u = x(1:3);
        v = x(4:6);
        w = x(7:9);
    end
end

